package com.koma.leetcode.medium.bst;

import com.koma.leetcode.ds.TreeNode;

import java.util.Stack;

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2020-03-15
 */
public class N173 {
    /**
     *
     * 实现原理：受控递归
     *
     */
    class BSTIterator {
        Stack<TreeNode> stack = new Stack<>();

        public BSTIterator(TreeNode root) {
            helper(root);
        }

        private void helper(TreeNode root) {
            while (root != null) {
                stack.push(root);
                root = root.getLeft();
            }
        }

        /** @return the next smallest number */
        public int next() {
            TreeNode top = stack.pop();
            if (top.getRight() != null) {
                helper(top.getRight());
            }
            return top.getVal();
        }

        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return stack.size() > 0;
        }
    }
}
